package com.ysxsoft.wdg.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.ysxsoft.wdg.util.transform.GlideRoundTransform;

import java.lang.reflect.Field;
import java.util.List;


/**
 * view常用的方法
 */
public class ViewUtils {


    //模糊效果
    public static Bitmap boxBlur(Bitmap bitmap, int radius) {
        final int width = bitmap.getWidth();
        final int height = bitmap.getHeight();
        final Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), bitmap.getConfig());
        final int[] pixels = new int[width * height];
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
        //纵向模糊
        for (int i = 0; i < width; i++) {
            int r = 0, g = 0, b = 0;
            int count = 0;
            //处理边界情况先将模糊半径内像素导入并求和
            for (int k = 0; k < radius; k++) {
                final int pixel = pixels[k * width + i];
                r += Color.red(pixel);
                g += Color.green(pixel);
                b += Color.blue(pixel);
                count++;
            }
            int headIndex = 0;

            // /纵向逐个像素移动
            for (int j = 0; j < height; j++) {
                //预测尾部位置
                int last = j + radius;
                //超过宽度则从和中减去队列头部像素
                if (last >= height) {
                    final int headPixel = pixels[headIndex * width + i];
                    r -= Color.red(headPixel);
                    g -= Color.green(headPixel);
                    b -= Color.blue(headPixel);
                    count--;
                    headIndex++;
                } else if (count <= 2 * radius + 1) {
                    //队列长度不足2 * radius + 1时向队列尾部添加新的像素
                    final int pixel = pixels[j * width + i];
                    r += Color.red(pixel);
                    g += Color.green(pixel);
                    b += Color.blue(pixel);
                    count++;
                } else { //队列长度益处后加入新像素，移除头部像素

                    final int headPixel = pixels[headIndex * width + i];
                    final int pixel = pixels[j * width + i];
                    r = r - Color.red(headPixel) + Color.red(pixel);
                    g = g - Color.green(headPixel) + Color.green(pixel);
                    b = b - Color.blue(headPixel) + Color.blue(pixel);
                    headIndex++;
                }
                pixels[j * width + i] = Color.rgb(r / count, g / count, b / count);
            }
        } //横向模糊
        for (int i = 0; i < height; i++) {
            int r = 0, g = 0, b = 0;
            int count = 0;
            for (int k = 0; k < radius; k++) {
                final int pixel = pixels[i * width + k];
                r += Color.red(pixel);
                g += Color.green(pixel);
                b += Color.blue(pixel);
                count++;
            }
            int headIndex = 0;
            for (int j = 0; j < width; j++) {
                int last = j + radius;
                if (last >= width) {
                    final int headPixel = pixels[i * width + headIndex];
                    r -= Color.red(headPixel);
                    g -= Color.green(headPixel);
                    b -= Color.blue(headPixel);
                    count--;
                    headIndex++;
                } else if (count <= 2 * radius + 1) {
                    final int pixel = pixels[i * width + j];
                    r += Color.red(pixel);
                    g += Color.green(pixel);
                    b += Color.blue(pixel);
                    count++;
                } else {
                    final int headPixel = pixels[i * width + headIndex];
                    final int pixel = pixels[i * width + j];
                    r = r - Color.red(headPixel) + Color.red(pixel);
                    g = g - Color.green(headPixel) + Color.green(pixel);
                    b = b - Color.blue(headPixel) + Color.blue(pixel);
                    headIndex++;
                }
                pixels[i * width + j] = Color.rgb(r / count, g / count, b / count);
            }
        }
        outBitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        bitmap.recycle();
        return outBitmap;
    }


    /**
     * QQ聊天
     */
    public static void toQQ(Context context, String qq) {
        try {
            if (isQQClientAvailable(context)) {
                String url = "mqqwpa://im/chat?chat_type=wpa&uin=" + qq;//uin是发送过去的qq号码
                context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            } else {
                ToastUtils.showToast("抱歉！请安装QQ");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断 用户是否安装QQ客户端
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equalsIgnoreCase("com.tencent.qqlite") || pn.equalsIgnoreCase("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }


    public static void setPricePoint(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }

        });

    }

    public static void call(Context context, String tel) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + tel));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


    public static void setTvPosition(int position, TextView[] textViews) {
        for (int i = 0; i < textViews.length; i++) {
            if (position == i) {
                textViews[i].setSelected(true);
            } else {
                textViews[i].setSelected(false);
            }
        }
    }

    public static void setIvPosition(int position, ImageView[] imageViews) {
        for (int i = 0; i < imageViews.length; i++) {
            if (position == i) {
                imageViews[i].setSelected(true);
            } else {
                imageViews[i].setSelected(false);
            }
        }
    }

    /**
     * 替换手机号中间四位为 ****
     *
     * @param mobiles
     * @return
     */
    public static String changeMobile(String mobiles) {
        try {
            return mobiles.substring(0, 3) + "****" + mobiles.substring(7, mobiles.length());
        } catch (Exception e) {
            return mobiles;
        }
    }

    /**
     * textView设置value
     */
    public static void setText(TextView tv, String value) {
        setText(tv, value, "");
    }

    /**
     * textView设置value
     */
    public static void setText(TextView tv, String value, String defaultValue) {
        if (!TextUtils.isEmpty(value)) {
            tv.setText(value);
        } else {
            tv.setText(defaultValue);
        }
    }

    public static boolean isEmpty(TextView textView) {
        return TextUtils.isEmpty(textView.getText().toString().trim());
    }

    public static boolean isNotEmpty(TextView textView) {
        return !isEmpty(textView);
    }

    public static boolean isNotEmpty(EditText editText) {
        return !isEmpty(editText);
    }

    /*
     *加载图片(默认)
     */
    public static void loadImage(Context context, String url, ImageView imageView) {
        RequestOptions options = new RequestOptions()
                .centerCrop()
                //                .placeholder(placeholderSoWhite) //占位图
                //                .error(R.color.white)       //错误图
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        Glide.with(context).load(url).apply(options).into(imageView);

    }

    /**
     * 加载圆形图片
     */
    public static void loadCircleImage(Context context, String url, ImageView imageView) {
        RequestOptions options = new RequestOptions()
                .centerCrop()
                .circleCrop()//设置圆形
                //                .placeholder(placeholderSoWhite)
                //                .error(errorSoWhite)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        Glide.with(context).load(url).apply(options).into(imageView);
    }

    /**
     * 加载圆角图片
     */
    public static void loadRoundCircleImage(Context context, String url, ImageView imageView) {
        RequestOptions options = RequestOptions//设置圆形
                //                .placeholder(placeholderSoWhite)
                //                .error(errorSoWhite)
                //.priority(Priority.HIGH)
                .bitmapTransform(new GlideRoundTransform())
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        Glide.with(context).load(url).apply(options).into(imageView);

    }

    /**
     * 隐藏软键盘
     */
    public static void closeKeyboard(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(((Activity) context).getWindow().getDecorView().getWindowToken(), 0);
        }
    }


    /**
     * 设置tablayout下划线长度和内容保持一致
     *
     * @param tabLayout
     */
    public static void tabRelex(final TabLayout tabLayout) {
        //了解源码得知 线的宽度是根据 tabView的宽度来设置的
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);

                    int dp10 = ScreenUtils.dpToPx(tabLayout.getContext(), 10);

                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);

                        //拿到tabView的mTextView属性  tab的字数不固定一定用反射取mTextView
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);
                        TextView mTextView = (TextView) mTextViewField.get(tabView);
                        tabView.setPadding(0, 0, 0, 0);

                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }

                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        params.leftMargin = dp10;
                        params.rightMargin = dp10;
                        tabView.setLayoutParams(params);

                        tabView.invalidate();
                    }
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });

    }


    public static void setDeletLine(TextView textView) {
        textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中间横线（删除线）
    }

    public static void setBottomLine(TextView textView) {
        textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
    }

    public static void setLine(TextView textView) {
        textView.getPaint().setAntiAlias(true);// 抗锯齿
    }

}
